/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.boot4g.admin.module.sys.service.impl;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.boot4g.admin.module.sys.service.PermissionService;
import com.boot4g.admin.module.sys.service.SysMenuService;
import com.boot4g.admin.security.SecurityUtils;
import com.boot4g.constant.GlobalConstant;
import com.google.common.base.Joiner;
import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.collection.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author lengleng
 * @date 2017/10/28
 */
@Slf4j
@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private SysMenuService menuService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        //ele-admin options 跨域配置，现在处理是通过前端配置代理，不使用这种方式，存在风险
//        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod())) {
//            return true;
//        }
        String currentLoginName = SecurityUtils.getCurrentLoginName();
        Set<String> currentAuthorityUrl = SecurityUtils.getCurrentAuthorityUrl();
        String requestURI = request.getRequestURI();
        log.info("验证权限loginName={}, requestURI={}, hasAuthorityUrl={}", currentLoginName, requestURI, Joiner.on(GlobalConstant.Symbol.COMMA).join(currentAuthorityUrl));
        // 超级管理员 全部都可以访问
//        if (org.apache.commons.lang3.StringUtils.equals(currentLoginName, GlobalConstant.Sys.SUPER_MANAGER_LOGIN_NAME)) {
//            return true;
//        }

        // DEMO项目Feign客户端具有所有权限, 如果需要则在角色权限中控制
//        if (currentLoginName.contains(OAUTH2_CLIENT_PREFIX)) {
//            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(currentLoginName);
//            return clientDetails != null;
//        }
        Boolean hasPermission = false;

        if (CollectionUtil.isEmpty(currentAuthorityUrl)) {
            log.warn("权限列表为空：{}", authentication.getPrincipal());
            return hasPermission;
        }

        Set<String> urlPermissions = new HashSet<String>();

        for (String urlPermission : currentAuthorityUrl) {
            if (StringUtils.isNotEmpty(urlPermission)) {//&& request.getMethod().equalsIgnoreCase(menu.getMethod())
                if(urlPermission.contains(",")) {
                    String[] urlArray = StringUtils.split(urlPermission,",");
                    for (String url : urlArray) {
                        if(antPathMatcher.match(url, request.getRequestURI())) {
                            hasPermission = true;
                            break;
                        }
                    }

                }else {
                    if(antPathMatcher.match(urlPermission, request.getRequestURI())){
                        hasPermission = true;
                        break;
                    }
                }

            }
        }
    return hasPermission;
    }
}
